package com.mxx.common.generator;

import com.alibaba.fastjson.annotation.JSONField;
import com.mxx.common.generator.db.TableColumn;
import com.mxx.common.utils.Strings;
import com.mysql.cj.MysqlType;
import lombok.Data;
import lombok.experimental.Accessors;

import java.lang.reflect.Field;
import java.util.*;
import java.util.function.Function;

@Data
@Accessors(chain = true)
public class EntityField {

    @JSONField(serialize = false)
    private EntityInfo entityInfo;
    private TableColumn tableColumn;
    private String fieldName;
    private String fieldClass;
    private String fieldClassName;
    private String remark;
    private MysqlType mysqlType;
    private Set<EntityAnno> annotationSet = new HashSet<>();
    private List<EntityInfo> generic = new ArrayList<>();

    public EntityField() {
    }

    public EntityField(Field field) {
        this.fieldName = field.getName();
        this.setFieldClass(field.getType());
    }
    public EntityField addAnno(EntityAnno entityAnno) {
        this.annotationSet.add(entityAnno);
        return this;
    }
    public EntityField setMysqlType(MysqlType mysqlType) {
        this.mysqlType = mysqlType;
        this.fieldClass = mysqlType.getClassName();
        this.fieldClassName = this.fieldClass.substring(this.fieldClass.lastIndexOf(".") + 1);
        return this;
    }

    public EntityField setFieldClass(Class classes) {
        this.setFieldClass(classes.getSimpleName(), classes.getName());
        return this;
    }

    public EntityField setFieldClass(String fieldClassName, String fieldClass) {
        this.fieldClassName = fieldClassName;
        this.fieldClass = fieldClass;
        return this;
    }

    public EntityField refreshRemark(Function<String, String> function) {
        this.remark = function.apply(this.remark == null ? "" : this.remark);
        return this;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof EntityField) {
            return this.fieldName.equals(((EntityField) obj).fieldName);
        }
        return super.equals(obj);
    }

    @Override
    public int hashCode() {
        return Objects.hash(fieldName);
    }

    @Override
    public String toString() {
        return fieldClass + " " + fieldName + (Strings.isEmpty(remark) ? "" : " (" + remark + ")");
    }
}
